from Controller.BaseController import BaseController
from Common.DuplicatedInstanceError import DuplicatedInstanceError
from Common.Client import Client
from Common.GroupOrg import Group
from Utility import FormData
from Utility import UserRole
from Utility import ViewName
from Utility import IsEmptyString
from Utility import TemplateValueName
from google.appengine.ext.db import BadKeyError

class CreateClientController(BaseController):
    """
    Let company admin create client and assign client to a company
    """
    def get(self):
        u = self.GetCurrentUser()

        # must be company admin
        if not self.VerifyCurrentUserRole(u, UserRole.User,"/create/client"):
            return
        # make sure current user is admin account
        # list all groups which belong the company which is associated with current user
        c = u.Ref_Company
        template_values = {'Groups': c.Groups, "CompanyName": c.CompanyName, "CompanyKey":c.key()}
        self.Render(ViewName.D_CREATECLIENT, template_values)
    
    
    def post(self):
        u = self.GetCurrentUser()
        
        # must be company admin
        if not self.VerifyCurrentUserRole(u, UserRole.User,"/create/client"):
            return
        
        clientName = self.request.get(FormData.CLIENT_NAME)
        groupKey = self.request.get(FormData.GROUP_KEY)
        
        c = u.Ref_Company        
        template_values = {'Groups': c.Groups, "CompanyName": c.CompanyName, "CompanyKey":c.key()}
        
        if IsEmptyString(groupKey):
            template_values[TemplateValueName.ERROR_MESSAGE]="Group id is invalid"
            return self.Render(ViewName.D_CREATECLIENT, template_values)
        
        try:
            g = Group.get(groupKey)
        except BadKeyError:
            template_values[TemplateValueName.ERROR_MESSAGE]="Group id is invalid"
            return self.Render(ViewName.D_CREATECLIENT, template_values)

        
        try:
            client = Client(parent = g.Ref_Company,
                     key_name=clientName,
                     ClientName=clientName,
                     Ref_Company = g.Ref_Company,
                     Ref_Group = g)
            client.TransactionPut()
            template_values[TemplateValueName.SUCCESS_MESSAGE]="New Client, "+clientName + ", was created successfully!"
        except DuplicatedInstanceError:
            template_values[TemplateValueName.ERROR_MESSAGE]="Client, "+clientName + ", already exists!"

        self.Render(ViewName.D_CREATECLIENT, template_values)
